package org.example.blog.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.blog.dao.CommentDao;
import org.example.blog.dao.LableDao;
import org.example.blog.pojo.Comment;
import org.example.blog.pojo.Label;
import org.example.blog.pojo.User;
import org.example.blog.response.ResponseResult;
import org.example.blog.services.IUserService;
import org.example.blog.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import java.util.Date;
import java.util.List;


@Transactional
@RestController
@RequestMapping("/test")
@Slf4j

public class testController {

    @Autowired
    private LableDao lableDao;

    @Autowired
    private IdWorker idWorker;

    @GetMapping("/hello")
    public ResponseResult helloworld(){
//        等价与
//        ResponseResult responseResult = new ResponseResult(ResponseState.SUCCESS);
//        responseResult.setData("helloWrold");
//        return responseResult;
        String captchaContent = (String) redisUtils.get(Constants.User.KEY_CAPTCHA_CONTENT + "123456");
        log.info("captchaContent =======> " + captchaContent);
        return ResponseResult.SUCCESS().setData("helloWrold");
    }

    @PostMapping("/label")
    public ResponseResult addLable(@RequestBody Label label){
        // 判断数据是否有效
        // 补全数据
        label.setId(idWorker.nextId() + "");
        label.setCreate_time(new Date());
        label.setUpdate_time(new Date());
        // 保存数据
        lableDao.save(label);
        return ResponseResult.SUCCESS("测试标签添加成功");
    }

    @DeleteMapping("/label/{labelId}")
    public ResponseResult deleteLabel(@PathVariable("labelId") String labelId){

        int deleteResult = lableDao.customDeleteLabelById(labelId);
//        log.info("sun  ====" + deleteResult);
        if(deleteResult > 0){
            return ResponseResult.SUCCESS("删除标签成功");
        }else {
            return ResponseResult.FAILED("标签不存在");
        }

    }


    @PutMapping("/label/{labelId}")
    public ResponseResult updateLabel(@PathVariable("labelId") String labelId, @RequestBody Label label){
        Label dbLabel = lableDao.findOneById(labelId);
        if (dbLabel == null){
            return ResponseResult.FAILED("标签不存在");
        }
        dbLabel.setCount(label.getCount());
        dbLabel.setName(label.getName());
        dbLabel.setCreate_time(new Date());
        dbLabel.setUpdate_time(new Date());
        lableDao.save(dbLabel);
        return ResponseResult.SUCCESS("修改成功");
    }

    @GetMapping("/label/{labelId}")
    public ResponseResult getlabelById(@PathVariable("labelId") String labelId, @RequestBody Label label){

        Label dbLabel = lableDao.findOneById(labelId);
        System.out.println(label.getName());
        if(dbLabel == null){
            return ResponseResult.FAILED("标签不存在");
        }
        return ResponseResult.SUCCESS("查询成功").setData(dbLabel);
    }

    @GetMapping("/label/list/{page}/{size}")
    public ResponseResult listLabel(@PathVariable("page") int page, @PathVariable("size") int size){
        if (page < 1 ){
            page = 1;
        }
        if (size <= 0){
            size = Constants.DEFAULT_SIZE;
        }
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Label> result = lableDao.findAll(pageable);
        return ResponseResult.SUCCESS("获取成功").setData(result);
    }

//    模糊查询
    @GetMapping("/label/search")
    public ResponseResult doLabelSearch(@RequestParam("keyword") String keyword, @RequestParam("count") int count){
        List<Label> all = lableDao.findAll(new Specification<Label>() {
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                Predicate namePre = cb.like(root.get("name").as(String.class), "%" + keyword + "%");
                Predicate countPre = cb.equal(root.get("count").as(Integer.class), count);
                Predicate and = cb.and(namePre, countPre);
                return and;
            }
        });
        if (all.size() == 0){
            return ResponseResult.FAILED("结果为空");
        }
        return ResponseResult.SUCCESS("查找成功").setData(all);
    }

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置字体
        // specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        specCaptcha.setFont(Captcha.FONT_1);
        // 设置类型，纯数字、纯字母、字母数字混合
        //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        String content = specCaptcha.text().toLowerCase();
        log.info("captcha content == > " + content);
        // 验证码存入session
        // request.getSession().setAttribute("captcha", content);
        // 保存到redis里，10分钟有效
        redisUtils.set(Constants.User.KEY_CAPTCHA_CONTENT + "123456", content, 60 * 10);


        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }


//    @GetMapping("/json")
//    public User json(){
////        User user = new User("张三", 15,"man");
////        return user;
//    }

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private IUserService userService;

    @PostMapping("/comment")
    public ResponseResult testComment(@RequestBody Comment comment, HttpServletRequest request, HttpServletResponse response){
        String content = comment.getContent();
        log.info("content === >" + content);
        // 还得知道是谁的评论，对这个评论，身份进行确定
        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKEN_KEY);
        System.out.println("comment tokenKey +" +tokenKey);
        if(tokenKey == null){
            return ResponseResult.ACCOUNT_NOT_LOGIN();

        }
        User user = userService.checkUser(request, response);


        if (user == null) {
            return ResponseResult.ACCOUNT_NOT_LOGIN();
        }

        comment.setUserId(user.getId());

        comment.setUserAvatar(user.getAvatar());

        comment.setUsername(user.getUsername());
        comment.setCreate_time(new Date());
        comment.setUpdate_time(new Date());
        comment.setId(idWorker.nextId() + "");
        commentDao.save(comment);
        return ResponseResult.SUCCESS("评论成功");
    }



}
